﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SimpleData.Storage.Common;
using System.Data.SqlClient;
using System.Diagnostics;
using System.Diagnostics.Contracts;

namespace SimpleData.Storage.SqlClient
{

	/// <summary>
	/// Salva os dados do documento no banco de dados SqlServer
	/// </summary>
	public class SqlStorageConnection : IStorageConnection
	{
		/// <summary>
		/// 
		/// </summary>
		public SqlStorageConnection( string csName )
		{
			Contract.Requires<ArgumentNullException>( !String.IsNullOrEmpty( csName ), "csName" );
			var config = System.Configuration.ConfigurationManager.ConnectionStrings[ csName ];
			string cs = String.Empty;

			if ( config != null )
				cs = config.ConnectionString;

			if ( String.IsNullOrEmpty( cs ) )
				throw new InvalidOperationException( String.Format( "String de conexão \"{0}\" inválida.", csName ) );
			this.ConnectionString = cs;
		}

		/// <summary>
		/// Obtém ou define o nome da string de conexão com o banco de dados
		/// </summary>
		public string ConnectionString
		{
			get;
			private set;
		}

		internal SqlConnection GetConnection()
		{
			SqlConnection connection = new SqlConnection( "" );
			connection.Open();
			return connection;
		}

		#region IStorageConnection Members

		public void InsertOrUpdate( DataObjectRow row )
		{
			// 
			UpdateCommandBuilder builder = new UpdateCommandBuilder();

			// Cria o comando SQL
			builder.IncludeColumnKey( row.Key );
			builder.IncludeColumnValues( row.Values );

			int rowsAffected = 0;
			using ( var conn = this.GetConnection() )
			{
				using ( var cmd = builder.CreateCommand( conn ) )
					rowsAffected = cmd.ExecuteNonQuery();

				conn.Close();
			}

			if ( rowsAffected != row.Values.Count() + 1 )
				throw new InvalidOperationException();
		}

		public void UpdatePartial( DataObjectRow row )
		{
			throw new NotImplementedException();
		}

		public void Delete( DataObjectColumnKey key )
		{
			throw new NotImplementedException();
		}

		#endregion
	}
}
